package logic

import (
	"context"
	"goods_srv/global"
	"goods_srv/goods_proto"
	"goods_srv/model"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

// 查询品牌列表
func (g *GoodsServer) BrandList(ctx context.Context, in *goods_proto.BrandFilterRequest) (*goods_proto.BrandListResponse, error) {
	brandListResponse := goods_proto.BrandListResponse{}
	var brands []model.Brands
	result := global.DB.Scopes(Paginate(int(in.Pages), int(in.PagePerNums))).Find(&brands)
	if result.Error != nil {
		return nil, result.Error
	}
	var count int64
	global.DB.Model(&model.Brands{}).Count(&count)
	brandListResponse.Total = int32(count)
	var brandResponse []*goods_proto.BrandInfoResponse
	for _, brand := range brands {
		brandResponse = append(brandResponse, &goods_proto.BrandInfoResponse{
			Id:   brand.ID,
			Name: brand.Name,
			Logo: brand.Logo,
		})
	}
	brandListResponse.Data = brandResponse
	return &brandListResponse, nil
}

// 新增品牌
func (g *GoodsServer) CreateBrand(ctx context.Context, in *goods_proto.BrandRequest) (*goods_proto.BrandInfoResponse, error) {
	if result := global.DB.Where("name = ?", in.Name).First(&model.Brands{}); result.RowsAffected == 1 {
		return nil, status.Errorf(codes.InvalidArgument, "商品品牌已存在")
	}
	brand := model.Brands{
		Name: in.Name,
		Logo: in.Logo,
	}
	tx := global.DB.Save(&brand)
	if tx.Error != nil {
		return nil, status.Errorf(codes.Internal, "新增品牌失败")
	}
	return &goods_proto.BrandInfoResponse{Id: brand.ID}, nil
}

// 删除品牌
func (g *GoodsServer) DeleteBrand(ctx context.Context, in *goods_proto.BrandRequest) (*goods_proto.Empty, error) {
	if result := global.DB.Delete(&model.Brands{}, in.Id); result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "品牌不存在")
	}
	return &goods_proto.Empty{}, nil
}

// 修改商品品牌
func (g *GoodsServer) UpdateBrand(ctx context.Context, in *goods_proto.BrandRequest) (*goods_proto.Empty, error) {
	var brand model.Brands
	if result := global.DB.First(&brand, in.Id); result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "商品品牌不存在")
	}
	brand.Name = in.Name
	brand.Logo = in.Logo
	tx := global.DB.Updates(&brand)
	if tx.Error != nil {
		return nil, status.Errorf(codes.Internal, "修改品牌失败")
	}
	return &goods_proto.Empty{}, nil
}
